import { defineStore } from 'pinia'
import api from '../services/api'

export const useDashboardStore = defineStore('dashboard', {
  state: () => ({
    summary: {
      device_status: {
        total: 0,
        online: 0,
        offline: 0,
        error: 0
      },
      today_production: 0,
      current_speed: 0,
      timestamp: null
    },
    devices: [],
    productionHistory: [],
    batches: [],
    loading: false,
    error: null
  }),

  actions: {
    async fetchDashboardSummary() {
      this.loading = true
      try {
        const response = await api.getDashboardSummary()
        this.summary = response.data
      } catch (error) {
        this.error = error.message || 'Failed to fetch dashboard summary'
        console.error('Error fetching dashboard summary:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchDeviceStatus() {
      this.loading = true
      try {
        const response = await api.getDeviceStatus()
        this.devices = response.data.devices
      } catch (error) {
        this.error = error.message || 'Failed to fetch device status'
        console.error('Error fetching device status:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchProductionHistory(period = 'day') {
      this.loading = true
      console.log('Store: Fetching production history for period:', period)
      try {
        const response = await api.getProductionHistory(period)
        console.log('Store: Production history API response:', response.data)
        this.productionHistory = response.data.data
        console.log('Store: Updated productionHistory state:', this.productionHistory)
      } catch (error) {
        this.error = error.message || 'Failed to fetch production history'
        console.error('Store: Error fetching production history:', error)
      } finally {
        this.loading = false
      }
    },

    async fetchProductionBatches(status = null) {
      this.loading = true
      try {
        const response = await api.getProductionBatches(status)
        this.batches = response.data.batches
      } catch (error) {
        this.error = error.message || 'Failed to fetch production batches'
        console.error('Error fetching production batches:', error)
      } finally {
        this.loading = false
      }
    },

    // For testing: simulate sending device data
    async sendTestDeviceData(deviceData) {
      try {
        const response = await api.sendDeviceData(deviceData)
        return response.data
      } catch (error) {
        this.error = error.message || 'Failed to send test device data'
        console.error('Error sending test device data:', error)
        throw error
      }
    }
  }
})
